import Vue from "vue"
import Vuex from "vuex"
import Db from "@/js/indexdb.js"
import { utils } from "@/js/utils.js"

Vue.use(Vuex)

// state：存储状态（变量）
// getters：对数据获取之前的再次编译，可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()
// mutations：修改状态，并且是同步的。在组件中使用$store.commit('',params)。这个和我们组件中的自定义事件类似。
// actions：异步操作。在组件中使用是$store.dispath('')
// modules：store的子模块，为了开发大型项目，方便状态管理而使用的。这里我们就不解释了，用起来和上面的一样。
export default new Vuex.Store({
    state: {
        messages: [],
        records: [],
        db: null,
        // 当前聊天对方
        // todo:改为session_id
        cur_from: "",
        cur_user: { phone: '' },
        entityList: [],
        isLogin: false,
        utils: new utils(),
        folderList: [],
        editingArticle: { content: '' },
        date: new Date(),
        satoken: '',
    },
    getters: {

    },
    mutations: {
        init(state) {
            state.db = new Db();
            state.db.initDB("pl", 4);
            console.log(state.db);
        },
        updateMessages(state, message) {
            state.messages.push(message);
        },
        updateAccount(state, newAccount) {
            if(newAccount) {
               state.cur_user = newAccount; 
            }
        },
        updateEntityList(state, newEntity) {
            state.entityList.push(newEntity);
        },
        setEditingArticle(state, value) {
            state.editingArticle = value;
        },
        setContent(state, content) {
            state.editingArticle.content = content;
        },
        appendContent(state, value, d) {
            Vue.set(state.editingArticle, 'content', state.editingArticle.content + value);
            state.date = d;
            console.log(state.editingArticle.content)
        },
        add(state, value) {
            state.date = value;
        },
        setToken(state, value) {
            state.satoken = value;
        },
    },
    actions: {
        async onRecOpenfireMsg({ state }, message) {
            try {
                // 如果当前正在聊天,那么消息同步到显示页面里
                if (message.from === state.cur_from) {
                    state.messages.push(message);
                    console.log(state.messages);
                }

                // 查看数据库中是否有记录
                // let record = await state.db.readRecordByFrom(message.from);
                // console.log(record.id);
                // if (record) {
                //     // 删除旧的记录
                //     state.db.removeRecord(record.id);
                // }
                // 会话记录同步到数据库
                console.log(state.records);
                let oldRecord = state.records.find(item => {
                    console.log(item)
                    if (item.from === message.from) {
                        return item;
                    }
                });
                console.log(oldRecord)
                let nid = '';
                if (oldRecord) {
                    nid = oldRecord.id;
                    // 更新
                    state.db.addRecord(nid, null, message.from, message.text, message.label, message.stamp);
                    state.records.splice(oldRecord);
                    console.log('rec update record:', nid);
                } else {
                    // nid = state.utils.getRandomString();
                    nid = await state.db.addRecord(null, null, message.from, message.text, message.label, message.stamp);
                    console.log('rec new record:', nid);
                    console.log(nid)
                }
                state.records.push({
                    id: nid,
                    session: null,
                    from: message.from,
                    avatar: null,
                    text: message.text,
                    label: message.label,
                    stamp: message.stamp
                });

                // 存储消息到数据库,其中text是数组类型
                state.db.addMessage(null, message.from, message.text, message.stamp, message.label, null);
            } catch (err) {
                console.log("error:", err)
            }
        },
        pushMessage({ state }, message) {
            try {
                console.log(message)
                // 存储消息到数据库
                state.db.addMessage(null, message.from, message.text, message.stamp, message.label, null);
                state.messages.push(message);
            } catch (err) {
                console.log(err);
            }

        },
        async pushRecord({ state }, record) {
            try {
                let oldRecord = state.records.find(item => {
                    console.log(item)
                    if (item.from === record.from) {
                        return item;
                    }
                });
                if (oldRecord) {
                    // 存在就更新
                    let id = await state.db.addRecord(oldRecord.id, record.session, record.from, record.text, record.label, record.stamp, record.avatar);
                    let nrecord = await state.db.readRecord(id);
                    state.records.splice(oldRecord);
                    console.log("update record:", nrecord);
                    state.records.push(nrecord);
                    console.log(state.records);
                } else {
                    let id = await state.db.addRecord(null, record.session, record.from, record.text, record.label, record.stamp, record.avatar);
                    let nrecord = await state.db.readRecord(id);
                    console.log("new record:", state.records);
                    state.records.push(nrecord);
                }

            } catch (err) {
                console.log(err);
            }

        },
        async loadRecord({ state }) {
            state.records = [];
            let cursor = await state.db.readAllRecord();
            if (cursor) {
                console.log("key:", cursor.key)
                state.records.push({
                    id: cursor.key,
                    session: cursor.value.session,
                    from: cursor.value.from,
                    avatar: cursor.value.avatar,
                    text: cursor.value.text,
                    label: cursor.value.label,
                    stamp: cursor.value.stamp,
                });
                cursor.continue();
            }
        },
        setFolderList({ state }, folders) {
            state.folderList = folders;
        },
        removeFolderItem({ state }, index) {
            state.folderList.splice(index, 1);
        },
    },
    modules: {

    }
})